package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	request "zong-go/app/http/requests"
	"zong-go/app/models"
	"zong-go/pkg/auth"
	"zong-go/pkg/cache"
	"zong-go/pkg/password"
	"zong-go/pkg/response"
)

type UserController struct {
	createRequest   request.UserCreateRequest
	updateRequest   request.UserUpdateRequest
	deleteRequest   request.UserDeleteRequest
	indexRequest    request.UserIndexRequest
	passwordRequest request.UserPasswordRequest
	model           models.User
}

// Create 创建用户
func (user *UserController) Create(context *gin.Context) {
	if err := context.ShouldBindJSON(&user.createRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}

	if _, err := user.model.GetByUsername(user.createRequest.Username); err == nil {
		response.ResponseError(context, "用户已存在")
		return
	}

	user.model.Username = user.createRequest.Username
	user.model.Name = user.createRequest.Name
	user.model.Phone = user.createRequest.Phone
	user.model.Password = password.Hash(user.createRequest.Password)
	user.model.Sex = user.createRequest.Sex
	user.model.Status = user.createRequest.Status

	if err := user.model.Create(); err != nil {
		response.ResponseError(context, err.Error())
	} else {
		response.ResponseSuccess(context, "success", user.model)
	}
}

// Update 更新用户
func (user *UserController) Update(context *gin.Context) {
	if err := context.ShouldBindJSON(&user.updateRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}

	_, err := user.model.Get(user.updateRequest.ID)
	if err != nil {
		response.ResponseError(context, "用户不存在")
		return
	}

	user.model.ID = user.updateRequest.ID
	user.model.Name = user.updateRequest.Name
	user.model.Phone = user.updateRequest.Phone
	if user.updateRequest.Sex != nil {
		user.model.Sex = user.updateRequest.Sex
	}
	if user.updateRequest.Status != nil {
		user.model.Status = user.updateRequest.Status
	}

	if err := user.model.Update(); err != nil {
		response.ResponseError(context, err.Error())
	} else {
		response.ResponseSuccess(context, "success", map[string]interface{}{})
	}
}

// Delete 删除用户
func (user *UserController) Delete(context *gin.Context) {
	if err := context.ShouldBindJSON(&user.deleteRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}

	if _, err := user.model.Get(user.deleteRequest.ID); err != nil {
		response.ResponseError(context, "用户不存在")
		return
	}

	user.model.ID = user.updateRequest.ID

	if err := user.model.Delete(); err != nil {
		response.ResponseError(context, err.Error())
	} else {
		response.ResponseSuccess(context, "success", map[string]interface{}{})
	}
}

// Index 用户列表
func (user UserController) Index(context *gin.Context) {
	if err := context.ShouldBindQuery(&user.indexRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}

	if user.indexRequest.ID > 0 {
		if one, err := user.model.Get(user.indexRequest.ID); err != nil {
			response.ResponseError(context, err.Error())
		} else {
			response.ResponseSuccess(context, "success", one)
		}
	} else {
		cond := map[string]interface{}{
			"username =": user.indexRequest.Username,
		}
		if all, err := user.model.GetAllPaging(context, cond); err != nil {
			response.ResponseError(context, err.Error())
		} else {
			response.ResponseSuccess(context, "success", all)
		}
	}
}

// Me 用户当前信息
func (user UserController) Me(context *gin.Context) {
	authorization := context.Request.Header.Get("Authorization")
	token, _ := auth.ParseToken(strings.Fields(authorization)[1])

	if !cache.Exists("UserCache_" + token.Id) {
		response.ResponseError(context, "success")
	} else {
		userCache := cache.Get("UserCache_" + token.Id)
		userData := fmt.Sprintf("%v", userCache) // interface{} 转 string
		currentUser := &models.ApiUser{}
		// json反序列化
		if err := json.Unmarshal([]byte(userData), currentUser); err != nil {
			response.ResponseError(context, "success")
		} else {
			response.ResponseSuccess(context, "success", currentUser)
		}
	}
}

// UpdatePassword 用户修改密码
func (user *UserController) UpdatePassword(context *gin.Context) {
	if err := context.ShouldBindQuery(&user.passwordRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}

	if u, err := user.model.GetByUsername(user.passwordRequest.Username); err != nil {
		response.ResponseError(context, "用户不存在")
		return
	} else {
		if ok := u.ComparePassword(user.passwordRequest.Password); !ok {
			response.ResponseError(context, "用户密码错误")
			return
		}

		if err := u.ResetPassword(password.Hash(user.passwordRequest.PasswordComfirm)); err != nil {
			response.ResponseError(context, err.Error())
		} else {
			response.ResponseSuccess(context, "success", u)
		}
	}
}
